#pragma once

#include <ServerStruct.h>
#include <Timer.h>

enum eIOHANDLER
{
	SERVER_IOHANDLER = 0,
	NUM_IOHANDER
};

class ServerSession;
class IOCPServer;
class NetworkObject;
struct MSG_BASE;

class ServerFrame
{
	friend NetworkObject *	DoAllocServerSession();
	friend VOID DoFreeServerSession( NetworkObject * pNetObject );
	friend VOID DoFreeConnectSession( NetworkObject * pNetObject );
public:
	ServerFrame(void);
	virtual ~ServerFrame(void);

public:
	
	VOID			UpdateServerTitle();
	virtual BOOL	DoInit();
	virtual VOID	DoRelease();
	virtual VOID	DoProcess();

	inline eSERVER_TYPE	GetServerType()	{ return GUILD_SERVER;	}

public:
	BOOL			SendDBProxy( MSG_BASE * pMsg, WORD wSize );
	BOOL			IsDBProxyServerConnected();

	BOOL			SendMaster( MSG_BASE * pMsg, WORD wSize );
	BOOL			IsMasterServerConnected();

	BOOL			SendWorld( MSG_BASE * pMsg, WORD wSize );
	BOOL			IsWorldServerConnected();

	inline VOID		Shutdown() { m_bShutdown = TRUE; }
	inline BOOL		IsServerInfoFromFile() { return m_bGetServerInfoFromFile; }

	inline VOID		SetServerKey( SERVER_KEY ServerKey ) { m_ServerKey = ServerKey; }
	inline SERVER_KEY	GetServerKey() { return m_ServerKey; }

	inline VOID		SetServerGUID( DWORD dwGuid ) { m_dwServerGUID = dwGuid; }
	inline DWORD	GetServerGUID() { return m_dwServerGUID; }

	VOID			SetDBProxyServerAddr( TCHAR* szDBProxyIP, WORD wDBProxyPort );
	VOID			SetWorldServerAddr( TCHAR* szWorldIP, WORD wWorldPort );

	VOID			ConnectToDBProxyServer();
	VOID			ConnectToWorldServer();

	inline VOID			Listen( char* szIP, WORD wPort )
	{
		SetListenAddr( szIP, wPort );
		Listen();
	}

	inline VOID		SetListenAddr( char* szIP, WORD wPort )
	{
		_tcsncpy( m_pszListenIP, szIP, 31 );
		m_wListenPort = wPort;
	}

protected:
	VOID			UpdateFPS();
	VOID			DisplayServerInfo();
	VOID			MaintainConnection();

protected:
	VOID			Listen();
	VOID			Connect();
	VOID			Connect( ServerSession * pNetObject, char * pszIP, WORD wPort );
	VOID			Update();
	BOOL			ProcessConsole();

private:
	char			m_pszListenIP[32];
	WORD			m_wListenPort;
	IOCPServer *	m_pIOCPServer;
	ServerSession * m_pDBProxyServerSession;
	ServerSession * m_pMasterServerSession;
	ServerSession * m_pWorldServerSession;
	// connection num
	INT				m_nConnectionNum;

	DWORD			m_dwFPS;
	util::Timer		m_ReconnectTimer;
	BOOL			m_bShutdown;

	BOOL			m_bGetServerInfoFromFile;
	SERVER_KEY		m_ServerKey;
	DWORD			m_dwServerGUID;
};

extern ServerFrame g_GuildServer;